package com.olocat.cjx.nsims.controller

import com.alibaba.fastjson.JSONObject
import com.olocat.cjx.nsims.dao.LoginCacheRepository
import com.olocat.cjx.nsims.pojo.cache.LoginCache
import com.olocat.cjx.nsims.pojo.permission.SmsCaptcha
import com.olocat.cjx.nsims.pojo.permission.Token
import com.olocat.cjx.nsims.pojo.personnel.User
import com.olocat.cjx.nsims.service.UserService
import com.olocat.cjx.nsims.util.Response
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.*
import sun.misc.BASE64Encoder
import java.sql.Timestamp
import java.util.*
import javax.annotation.Resource

@RestController
@RequestMapping("api")
class LoginController {

    @Resource
    lateinit var userService: UserService

    @Resource
    lateinit var loginCacheRepository: LoginCacheRepository
    val log = LoggerFactory.getLogger("LoginController")!!

    val encoder = BASE64Encoder()
    var captcha: Int = 0
    var user: User? = null

    @PostMapping("/auth/login")
    fun login(@RequestBody result: JSONObject): Response {
        log.info("登录验证")
        if (result.containsKey("username")) {
            val username = result["username"].toString()
            val password = result["password"].toString()
            log.info("登录信息：$result")
            log.info("username: $username")
            log.info("password: $password")
            user = userService.login(username, password)
            return if (user != null) {
                val token = JSONObject()
                val tokenString = encoder.encode((user!!.id + user!!.telephone + Date().time).toByteArray())
                token["token"] = tokenString
                log.info("账号密码登录成功 token: $token")
                log.info("id: ${user!!.id}")
                if (loginCacheRepository.existsByUserId(user!!.id!!)) {
                    log.info("用户已存在")
                    loginCacheRepository.deleteById(user!!.id!!)
                }
                loginCacheRepository.save(LoginCache(user!!.id!!, tokenString, Timestamp(Date().time), ""))
                Response.builder(token, 200)
            } else {
                log.info("账号密码登录验证失败!")
                Response.builder(null, "账号或密码错误!", 401)
            }
        } else {
            val mobile = result["mobile"].toString()
            val user = userService.getByTelephone(mobile)
            println("mobile: ${result["mobile"]}")
            println("captcha: ${result["captcha"]}")
            println("real captcha: ${this.captcha}")
            println(user)
            return if (captcha == 0 || result["captcha"].toString().toInt() != captcha || user == null) {
                log.info("验证码登录验证失败!")
                Response.builder(null, "验证码错误或手机号未注册", 401)
            } else {
                val tokenString = encoder.encode((user.id + user.telephone + Date().time).toByteArray())
                val token = Token(tokenString)
                log.info("验证码登录成功 token: ${token.token}")
                loginCacheRepository.save(LoginCache(user.id!!, tokenString, Timestamp(Date().time), ""))
                Response.builder(token, 200)
            }
        }
    }

    //    @RequestMapping("user/info")
    fun info(): Response {
        println("go in /api/user/info")
        return Response.builder(user)
    }

    @RequestMapping("auth/logout")
    fun logout(@RequestHeader("Access-Token") token: String): Response {
        log.info("go in /api/auth/logout")
        loginCacheRepository.removeByUserToken(token)
        return Response.builder()
    }

    @RequestMapping("account/sms")
    fun sms(): Response {
        this.captcha = (Math.random() * 899999 + 100000).toInt()
        return Response.builder(SmsCaptcha(captcha))
    }

}